/*
 * Created by Jaren at 2021/10/28 17:43
 */
import 'package:ble_plugin/ble_device_filter.dart';
import 'package:ble_plugin/ble_plugin.dart';
import 'package:ble_plugin/ble_uuid.dart';
import 'package:ble_plugin_example/base/base.dart';
import 'package:ble_plugin_example/operation/operation_controller.dart';
import 'package:ble_plugin_example/operation/operation_view.dart';
import 'package:ble_plugin_example/widget/prompt.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';

class SearchBLEController extends BaseController {
  static final _bleUuid1 = BleUuid(
      "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
      "6e400002-b5a3-f393-e0a9-e50e24dcca9e",
      "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
      "6e400003-b5a3-f393-e0a9-e50e24dcca9e");
  static final _bleUuid2 = BleUuid(
      "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
      "6e400002-b5a3-f393-e0a9-e50e24dcca9e",
      "6e400001-b5a3-f393-e0a9-e50e24dcca9e",
      "6e400003-b5a3-f393-e0a9-e50e24dcca9e");

  // 扫描到的设备列表
  final devices = <BluetoothDevice>[].obs;

  RxBool searching = false.obs;
  RxBool connecting = false.obs;

  // 当前系统蓝牙状态
  Rx<BluetoothAdapterState> btState = BluetoothAdapterState.unknown.obs;

  BleManager _bleManager = BleManager();

  @override
  init() {
    _bleManager.getBtState().then((value) => btState.value = value);
    _bleManager.addSupportedBleServices([
      _bleUuid1,
      _bleUuid2,
    ]);
    _bleManager.onStateChangedCallback = _onBtDeviceStateChangedCallback;
  }

  bool scan() {
    if (btState.value != BluetoothAdapterState.on) {
      return false;
    }
    if (searching.value) return true;
    devices.clear();
    _bleManager.scan(filter: BleDeviceNameFilter("^.+-[0-9A-F]{8}\$")).listen(
        (scanResult) {
      devices.add(scanResult.device);
    }, onError: (e) {
      if (e is ScanTooFrequentlyException) {
        print(
            "Wait ${e.millisecondsLeft} seconds and then retry to scan again.");
      }
      print(e);
    }, onDone: () => searching.value = false);

    searching.value = true;
    return true;
  }

  bool stopScanning() {
    if (btState.value != BluetoothAdapterState.on) {
      return false;
    }
    _bleManager.stopScan();
    searching.value = false;
    return true;
  }

  connect({BluetoothDevice? device, String? name}) {
    if (searching.value) stopScanning();
    _bleManager.connect(
        device: device,
        name: name,
        flag: 'HOME_SEARCH',
        timeoutCallback: () {
          print("connect timeout");
        });
  }

  showConnectingDialog() {
//        Get.find<LoadingController>().showLoading();
  }

  OnStateChanged _onBtDeviceStateChangedCallback =
      (device, state, {String? flag}) {
    print(
        "bt state changed, device: ${device.advName}, state: $state, flag: $flag");
    switch (state) {
      case BluetoothConnectionState.disconnected:
        Prompt.showMessageDialog('Device has disconnected');
        break;
      case BluetoothConnectionState.connecting:
        break;
      case BluetoothConnectionState.connected:
        Prompt.showToast('Device has connected');
        Get.to(OperationPage(), binding: BindingsBuilder(() {
          Get.lazyPut(() => OperationController());
        }));
        break;
      case BluetoothConnectionState.disconnecting:
        break;
    }
  };
}
